
/*
    依赖于全局的jquery，此处作为UMD引入依赖
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.Tab = factory();
    }
}(this, function () {
    function Tab(args){
        var options = args || {}
        this.$wrap = options.$wrap || $('body');
        this.$tabLable = this.$wrap.find('[tab-lable]');
        this.$tabBody = this.$wrap.find('[tab-body]');//优先tab-body 多个
        this.$ifameBody = this.$wrap.find('[tab-iframe]');//ifame DIV包裹 唯一切换 注意DOM中的配置方式

        this.eventType = options.eventType || 'click';
        this.beforefn = options.beforefn || function(){};
        this.afterfn = options.afterfn || function(){};

        this.init = options.init;//这个是函数

        this.addEvent();
        if(Object.prototype.toString.call(this.init)=== '[object Function]'){
            this.init.call(this);
        }
    }
    Tab.prototype = {
        constructor:Tab,
        addEvent:function(){
            var self = this;
            this.$tabLable.on(this.eventType, function(event){
                if(this.tagName=='A'){
                    event.preventDefault();
                }
                if(self.$tabBody.length>0){
                    self.tabBodyChange.call(self, event, this);
                }else{
                    self.ifameBodyChange.call(self, event, this);
                }
            });
        },
        tabBodyChange:function(event, element){
            var target = element,
                index = target.getAttribute("tab-lable");
            if(!index){ return; }
            this.beforefn.apply(this, [event, target]);
            this.$tabBody.hide();
            $('[tab-body='+index+']').show();
            this.afterfn.apply(this, [event, target]);
        },
        ifameBodyChange:function(event, element){
            var target = element,
                name = target.getAttribute("tab-ifame-name"),
                contextPath = this.$ifameBody[0].getAttribute("contextPath");
            if(!name){ return; }
            this.beforefn.apply(this, [event, target]);
            this.$ifameBody.find('iframe')[0].src = contextPath + name;
            // ifame异步
            this.afterfn.apply(this, [event, target]);
        },
        tabSwitch:function(index){
            var self = this;
            var $el = this.$wrap.find('[tab-lable="'+ index +'"]');
            $el.trigger(this.eventType);
            return {
                $tabLable:self.$tabLable,
                $tabBody:self.$tabBody,
                $ifameBody:self.$ifameBody
            }
        }
    }
    return Tab
}));